<template>
  <GlobalBG title="事件列表" :showBack="true" :showCollege="false">
    <view class="event-list-container">
      <!-- 搜索区域 -->
      <view class="search-section">
        <view class="search-box">
          <input
            placeholder="搜索事件名称/地点"
            class="search-input"
            disabled
          />
          <view class="search-icon">
            <image
              class="search-img"
              src="/static/images/xgjd/search.png"
              alt="搜索图标"
            />
          </view>
        </view>
      </view>

      <!-- 排序与筛选区域 -->
      <view class="sort-filter-section">
        <view class="left-control">
          <view class="sort-control">
            <text>排序</text>
          </view>
          <view
            class="sort-item"
            :class="{ active: currentSort === 'severity' }"
          >
            <text>紧急程度</text>
            <image
              class="sort-arrow"
              :src="
                currentSort === 'severity'
                  ? '/static/images/sortBlue.png'
                  : '/static/images/sortBlack.png'
              "
            ></image>
          </view>
          <view class="sort-item" :class="{ active: currentSort === 'latest' }">
            <text>最新事件</text>
            <image
              class="sort-arrow"
              :src="
                currentSort === 'latest'
                  ? '/static/images/sortBlue.png'
                  : '/static/images/sortBlack.png'
              "
            ></image>
          </view>
        </view>
        <view class="right-control" @click="openFilterModal">
          <text class="filter-button">筛选</text>
          <image class="sort-arrow" src="/static/images/select.png"></image>
        </view>
      </view>

      <!-- 筛选弹窗（使用 uni-popup） -->
      <uni-popup
        ref="popupRef"
        type="bottom"
        :mask-click="false"
        :duration="300"
      >
        <view class="filter-modal">
          <view class="modal-header">
            <text class="modal-title">筛选</text>
            <view class="modal-close" @click="closeAndResetFilterModal">
              <image src="../../static/images/close.png" alt="关闭" />
            </view>
          </view>

          <scroll-view class="scroll-view" scroll-y="true">
            <!-- 筛选条件 -->
            <view class="filter-section">
              <text class="filter-label">事件类型</text>
              <view class="filter-options">
                <view
                  v-for="(item, index) in eventTypes"
                  :key="index"
                  :class="[
                    'filter-option',
                    { active: selectedEventTypes === item.code }, // 单选高亮逻辑
                  ]"
                  @click="toggleEventType(item)"
                >
                  {{ item.text }}
                </view>
              </view>
            </view>

            <view class="filter-section">
              <text class="filter-label">事件等级</text>
              <view class="filter-options">
                <view
                  v-for="(item, index) in eventLevels"
                  :key="index"
                  :class="[
                    'filter-option',
                    { active: selectedEventLevels === item.code }, // 单选高亮逻辑
                  ]"
                  @click="toggleEventLevel(item)"
                >
                  {{ item.text }}
                </view>
              </view>
            </view>

            <view class="filter-section">
              <text class="filter-label">时间范围</text>
              <view class="filter-options">
                <view
                  v-for="(item, index) in timeRanges"
                  :key="index"
                  :class="[
                    'filter-option',
                    { active: selectedTimeRange === item.code }, // 单选高亮逻辑
                  ]"
                  @click="setTimeRange(item)"
                >
                  {{ item.text }}
                </view>
              </view>
            </view>

            <view class="filter-section">
              <text class="filter-label">事件状态</text>
              <view class="filter-options">
                <view
                  v-for="(item, index) in eventStatuses"
                  :key="index"
                  :class="[
                    'filter-option',
                    { active: selectedEventStatuses === item.code }, // 单选高亮逻辑
                  ]"
                  @click="toggleEventStatus(item)"
                >
                  {{ item.text }}
                </view>
              </view>
            </view>

            <view class="filter-section">
              <text class="filter-label">选择社区</text>
              <view class="filter-options">
                <view
                  v-for="(item, index) in communities"
                  :key="index"
                  :class="[
                    'filter-option',
                    { active: selectedCommunities === item.code }, // 单选高亮逻辑
                  ]"
                  @click="toggleCommunity(item)"
                >
                  {{ item.text }}
                </view>
              </view>
            </view>
          </scroll-view>

          <view class="filter-buttons">
            <button class="reset-button" @click="resetFilters">重置</button>
            <button class="confirm-button" @click="applyFilters">确认</button>
          </view>
        </view>
      </uni-popup>

      <!-- 事件列表区域 -->
      <view class="event-list">
        <scroll-view
          class="scroll-view"
          scroll-y="true"
          :refresher-enabled="true"
          :refresher-triggered="refresherTriggered"
          @refresherrefresh="handleRefresh"
          @scrolltolower="handleLoadMore"
          style="width: 100%"
        >
          <view
            v-for="(incident, index) in incidents"
            :key="index"
            class="incident-item"
            @click="handleIncidentClick(incident)"
            style="width: 100%"
          >
            <view class="status-container">
              <text
                class="status-label"
                :data-status="incident.status"
                :class="`status-label-${getStatusTagColor(
                  incident.eventStatusCode
                )}`"
              >
                {{ incident.status }}
              </text>
            </view>
            <image
              :src="incident.pic || '/static/default-thumbnail.png'"
              class="pic"
              mode="aspectFill"
            ></image>
            <view class="content">
              <text class="title">{{ incident.title }}</text>
              <view class="details">
                <text>时间：{{ incident.eventTime }}</text>
                <text>地点：{{ incident.location }}</text>
              </view>
              <view class="status-tags">
                <text
                  class="status-tag"
                  :class="`status-tag-${getStatusTagColor(
                    incident.eventClassCode
                  )}`"
                >
                  {{ incident.eventClass }}
                </text>
                <text
                  class="status-tag"
                  :class="`status-tag-${getStatusTagColor(
                    incident.eventSourceCode
                  )}`"
                >
                  {{ incident.eventSource }}
                </text>
              </view>
            </view>
          </view>

          <!-- 显示空白图片 -->
          <view v-if="incidents.length === 0" class="empty-tip-container">
            <image
              src="/static/images/searchKong.png"
              class="empty-tip"
              alt="空白提示"
            />
            <text class="empty-tip-text">没有找到相关事件</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </GlobalBG>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import api from '@/api/modules/event';

// 定义事件项类型
interface Incident {
  id: string;
  pic: string;
  title: string;
  eventTime: string;
  location: string;
  status: string;
  eventClass: string;
  eventClassCode: string;
  eventCode: string;
  eventSource: string;
  eventSourceCode: string;
  eventStatusCode: string;
  eventType: string;
  eventLevel: string;
  community: string;
  severity?: number; // 紧急程度数值
}

// 定义筛选条件的状态变量
const selectedEventTypes = ref<string>('');
const selectedEventLevels = ref<string>('');
const selectedTimeRange = ref<string>('');
const selectedEventStatuses = ref<string>('');
const selectedCommunities = ref<string>('');

// 定义筛选条件的选项数组
const eventTypes = ref<FilterOption[]>([]);
const eventLevels = ref<FilterOption[]>([]);
const timeRanges = ref<FilterOption[]>([
  { text: '全部', code: '' },
  { text: '今天', code: '1' },
  { text: '本周', code: '7' },
  { text: '本月', code: '30' },
]);
const eventStatuses = ref<FilterOption[]>([]);
const communities = ref<FilterOption[]>([]);

// 事件数据示例
const incidents = ref<Incident[]>([]);
// 定义分页参数对象
const paginationParams = ref({
  pageNum: 1,
  pageSize: 10, // 默认查10条
  eventClass: '', //事件等级
  eventStatus: '', //事件状态
  orgId: '', //社区ID
  eventCode: '', //事件类型
  period: '', //时间范围
});

// 弹窗引用
const popupRef = ref<InstanceType<typeof UniPopup>>();
// 刷新状态变量
const refresherTriggered = ref(false);

// 初始化所有数据
const initializeData = async () => {
  try {
    // 获取社区列表
    const communityRes = await api.getSqList();
    communities.value = [
      { text: '全部', code: '' },
      ...communityRes.data.map((item: any) => ({
        text: item.orgName,
        code: item.orgId,
      })),
    ];

    // 获取事件类型列表
    const eventTypeRes = await api.getEventTypeList();
    eventTypes.value = [
      { text: '全部', code: '' },
      ...eventTypeRes.data.map((item: any) => ({
        text: item.eventDefineDisplay,
        code: item.eventDefine,
      })),
    ];

    // 获取事件等级列表
    const eventLevelRes = await api.getsjjdList();
    eventLevels.value = [
      { text: '全部', code: '' },
      ...eventLevelRes.data.map((item: any) => ({
        text: item.eventClassDisplay,
        code: item.eventClass,
      })),
    ];

    // 获取事件状态列表
    const eventStatusRes = await api.getczztList();
    eventStatuses.value = [
      { text: '全部', code: '' },
      ...eventStatusRes.data.map((item: any) => ({
        text: item.eventStatusDisplay,
        code: item.eventStatus,
      })),
    ];

    // 获取事件列表
    await fetchIncidentList();
  } catch (error) {
    console.error('初始化数据失败', error);
  }
};

// 初始化时调用接口获取数据
onLoad(async () => {
  await initializeData();
});
// 页面显示时调用接口获取数据
onShow(async () => {
  await fetchIncidentList();
});
// 获取事件列表
const fetchIncidentList = async () => {
  try {
    const params = {
      pageNum: paginationParams.value.pageNum,
      pageSize: paginationParams.value.pageSize,
      eventClass: paginationParams.value.eventClass,
      eventStatus: paginationParams.value.eventStatus,
      orgId: paginationParams.value.orgId,
      eventCode: paginationParams.value.eventCode,
      period: paginationParams.value.period,
    };
    console.log('获取事件列表参数', params);
    const res = await api.getbusizeventlist(params);
    if (paginationParams.value.pageNum === 1) {
      incidents.value = res.data.busizEventList.map((item: any) => ({
        busizEventId: item.busizEventId,
        pic: item.pic || '',
        title: item.eventName,
        eventTime: item.eventTime,
        location: item.address,
        status: item.eventStatus,
        eventCode: item.eventCode,
        eventClass: item.eventClass,
        eventClassCode: item.eventClassCode,
        eventSourceCode: item.eventSourceCode,
        eventSource: item.eventSource,
        eventType: item.eventName,
        eventLevel: item.eventClass,
        eventStatusCode: item.eventStatusCode,
        community: item.orgName,
        severity:
          item.eventClass === '紧急' ? 3 : item.eventClass === '重点' ? 2 : 1,
      }));
    } else {
      incidents.value = [
        ...incidents.value,
        ...res.data.busizEventList.map((item: any) => ({
          busizEventId: item.busizEventId,
          pic: item.pic || '',
          title: item.eventName,
          eventTime: item.eventTime,
          location: item.address,
          status: item.eventStatus,
          eventCode: item.eventCode,
          eventClass: item.eventClass,
          eventClassCode: item.eventClassCode,
          eventSourceCode: item.eventSourceCode,
          eventSource: item.eventSource,
          eventType: item.eventName,
          eventLevel: item.eventClass,
          eventStatusCode: item.eventStatusCode,
          community: item.orgName,
          severity:
            item.eventClass === '紧急' ? 3 : item.eventClass === '重点' ? 2 : 1,
        })),
      ];
    }
    console.log('获取事件列表成功', incidents.value);
  } catch (error) {
    console.error('获取事件列表失败', error);
  }
};

// 更新单选逻辑，点击时只选中一个选项
const toggleFilterOption = (
  selectedValue: Ref<string>,
  option: FilterOption
) => {
  const code = option.code;

  if (code === 'all') {
    // 点击"全部"选项
    selectedValue.value = '';
    return;
  }

  selectedValue.value = code;
};
// 事件类型
const toggleEventType = (type: FilterOption) => {
  toggleFilterOption(selectedEventTypes, type);
};

// 事件等级
const toggleEventLevel = (level: FilterOption) => {
  toggleFilterOption(selectedEventLevels, level);
};

// 时间范围
const setTimeRange = (range: FilterOption) => {
  toggleFilterOption(selectedTimeRange, range);
};

// 事件状态
const toggleEventStatus = (status: FilterOption) => {
  toggleFilterOption(selectedEventStatuses, status);
};

// 社区
const toggleCommunity = (community: FilterOption) => {
  toggleFilterOption(selectedCommunities, community);
};

// 重置筛选条件
const resetFilters = () => {
  selectedEventTypes.value = '';
  selectedEventLevels.value = '';
  selectedTimeRange.value = '';
  selectedEventStatuses.value = '';
  selectedCommunities.value = '';

  // 重置 paginationParams
  paginationParams.value.eventClass = '';
  paginationParams.value.eventStatus = '';
  paginationParams.value.orgId = '';
  paginationParams.value.eventCode = '';
  paginationParams.value.period = '';
  fetchIncidentList();
};

// 应用筛选条件
const applyFilters = () => {
  console.log('应用筛选条件', selectedEventLevels.value);
  console.log('应用筛选条件111', selectedEventStatuses.value);
  paginationParams.value.eventClass = selectedEventLevels.value;
  paginationParams.value.eventStatus = selectedEventStatuses.value;
  paginationParams.value.orgId = selectedCommunities.value;
  paginationParams.value.eventCode = selectedEventTypes.value;
  paginationParams.value.period = selectedTimeRange.value;
  fetchIncidentList();
  closeFilterModal();
};

// 格式化时间显示
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date
    .getMinutes()
    .toString()
    .padStart(2, '0')}`;
};

// 点击事件项--跳转详情
const handleIncidentClick = (incident: Incident) => {
  uni.navigateTo({
    url: `/pages/czlist/detail?busizEventId=${incident.busizEventId}`,
  });
};

// 上拉刷新逻辑
const handleRefresh = () => {
  refresherTriggered.value = true;
  uni.showLoading({ title: '刷新中...' });
  paginationParams.value.pageNum = 1; // 重置页码
  incidents.value = []; // 清空事件列表
  fetchIncidentList().finally(() => {
    refresherTriggered.value = false;
    uni.hideLoading();
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000,
    });
  });
};

// 下拉加载更多逻辑
const handleLoadMore = () => {
  paginationParams.value.pageNum += 1; // 增加页码
  fetchIncidentList();
};

// 打开筛选弹窗
const openFilterModal = () => {
  popupRef.value?.open();
};

// 关闭筛选弹窗
const closeFilterModal = () => {
  popupRef.value?.close();
};

// 关闭筛选弹窗并重置筛选条件
const closeAndResetFilterModal = () => {
  resetFilters();
  closeFilterModal();
};

// 定义颜色映射函数
const getStatusTagColor = (statusCode: string): string => {
  switch (statusCode) {
    case '301':
      return 'urgent';
    case '101':
      return 'normal';
    case '201':
      return 'important';
    // 事件
    case '200':
      return 'intelligence';
    case '100':
      return 'artificial';
    case '110':
      return 'patrol';
    // 状态
    case '99':
      return 'wc';
    case '10':
      return 'cz';
    case '0':
      return 'zp';
    default:
      return 'normal';
  }
};
</script>

<style lang="scss" scoped>
// 整体容器
.event-list-container {
  padding: 20rpx;
  width: 100%;
  max-width: 900rpx;
  margin: 0 auto;
  background: #f6f9ff;
  display: flex;
  flex-direction: column;
  height: 100vh; /* 确保容器占满整个视口 */
}

// 搜索区域
.search-section {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
  border-radius: 15rpx;
}

.search-box {
  display: flex;
  align-items: center;
  width: 94%;
  height: 87rpx;
  background: #ffffff;
  border-radius: 10rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-family: PingFangSC, PingFang SC;
  background-color: transparent;
  border: none;
  padding: 0 20rpx;
  line-height: 70rpx;
}

.search-icon {
  cursor: pointer;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-img {
  width: 40rpx;
  height: 40rpx;
}

// 排序与筛选区域
.sort-filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 27rpx;
  line-height: 54rpx;
}

.left-control {
  display: flex;
  gap: 10rpx;
}

.sort-control {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  color: #999999;
  font-style: normal;
}

.sort-item {
  display: flex;
  align-items: center;
  gap: 5rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  color: #333333;
  font-style: normal;
  margin-left: 10rpx;
  cursor: pointer;
}

.sort-arrow {
  width: 35rpx;
  height: 35rpx;
}

// 选中状态
.active {
  color: #2266bf;
  border-color: #2263bf;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(70, 102, 149, 0.12);
  border-radius: 12rpx;
  padding: 0rpx 10rpx;
}

.right-control {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
  color: #333333;
  line-height: 38rpx;
  cursor: pointer;
}

.filter-button {
  margin-right: 10rpx;
}

// 事件列表区域
.event-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  flex: 1; // 使事件列表区域占据剩余空
  height: calc(100vh - 300rpx); /* 根据实际情况调整 */
}

.incident-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  height: 223rpx;
  padding: 25rpx;
  background: #ffffff;
  border-radius: 10rpx;
  position: relative;
  cursor: pointer;
  width: 100%;
  margin-bottom: 20rpx;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 27rpx;
  color: #333333;
  line-height: 38rpx;
  text-align: left;
  font-style: normal;
}

.details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 23rpx;
  color: #999999;
}

.status-tags {
  display: flex;
  gap: 10rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 23rpx;
  line-height: 33rpx;
}

.status-tag {
  margin-top: 10rpx;
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  &-urgent {
    background: #ffe6e6;
    color: #ff2121;
  }
  &-normal {
    background: #d2f0ff;
    color: #45aff7;
  }
  &-important {
    background: #ffe9d2;
    color: #ff982b;
  }
  &-intelligence {
    background: #c5f1e6;
    color: #39aa92;
  }
  &-artificial {
    background: #d2f0ff;
    color: #45aff7;
  }
  &-patrol {
    background: #e2e1ff;
    color: #9053ff;
  }
}

.status-container {
  position: absolute;
  top: -6rpx;
  right: 20rpx;
  z-index: 1;
}

.pic {
  width: 269rpx;
  height: 169rpx;
  background: #e8edf6;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.status-label {
  border-radius: 0rpx 0rpx 8rpx 8rpx;
  padding: 4rpx 12rpx;
  font-size: 22rpx;
  color: #fff;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  line-height: 33rpx;
  font-style: normal;
  &-wc {
    background: #c5f1e6;
    color: #39aa92;
  }
  &-cz {
    background: #ffe9d2;
    color: #ff982b;
  }
  &-zp {
    background: #e2e1ff;
    color: #9053ff;
  }
}

// 弹窗样式
.filter-modal {
  width: 100%;
  max-width: 600px;
  background: #ffffff;
  border-radius: 58rpx 58rpx 0rpx 0rpx;
  padding: 0;
  margin: 0 auto;
  height: 1327rpx;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  padding: 40rpx 0;
  background: #ffffff;
  border-radius: 58rpx 58rpx 0rpx 0rpx;
  border: 2rpx solid #e9e9e9;
  margin-bottom: 30rpx;
}

.modal-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 33rpx;
  color: #000000;
  line-height: 42rpx;
  font-style: normal;
  text-align: center;
  flex: 1;
}

.modal-close {
  position: absolute;
  right: 30rpx;
  cursor: pointer;
  image {
    width: 60rpx;
    height: 60rpx;
  }
}

.filter-section {
  margin-bottom: 20px;
  padding: 0 20px;
}

.filter-label {
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: bold;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 20rpx;
}

.filter-option {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 25rpx;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  &.active {
    color: #fff;
    background: rgba(142, 191, 255, 0.72);
    border-radius: 25rpx;
    font-weight: 500;
    font-size: 27rpx;
    color: #2263bf;
    line-height: 38rpx;
    text-align: right;
    font-style: normal;
  }
}

.filter-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: auto;
  margin-bottom: 40rpx;
  padding: 60rpx;
  height: 100rpx;
  line-height: 100rpx;
}

.reset-button,
.confirm-button {
  flex: 1;
  border-radius: 16rpx;
  font-weight: 500;
  font-size: 30rpx;
  color: #fff;
  cursor: pointer;
  border: none;
  text-align: center;
  margin: 0 20rpx;
  height: 70rpx; // 设置按钮的高度
  line-height: 70rpx;
  display: flex; // 使用 flex 布局
  align-items: center; // 文字垂直居中
  justify-content: center; // 文字水平居中
  padding: 0; // 清除 padding，确保文字不偏移
}

.reset-button {
  background-color: #999;
}

.confirm-button {
  background-color: #2263bf;
}

.scroll-view {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden; // 确保没有横向滚动条
  width: 100%;
  height: 100%; // 确保 scroll-view 占据剩余高度
}

// 空白提示样式
.empty-tip-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  // 确保容器占据剩余空间
  flex: 1;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
  height: 100%; // 确保容器占满整个事件列表区域的高度
}

.empty-tip {
  width: 315rpx;
  height: 242rpx;
  margin: 0 auto;
  display: block;
}

.empty-tip-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
  text-align: center;
}
</style>
